package com.loyalove.zerone.auth.config;

import com.loyalove.zerone.auth.bean.UserInfo;
import com.loyalove.zerone.auth.bean.UserInfoDetails;
import java.util.Map;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;

/**
 * @author loyalove
 */
public class JwtTokenConverter extends JwtAccessTokenConverter {


  /**
   * 生成token
   * @param accessToken
   * @param authentication
   * @return
   */
  @Override
  public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
    DefaultOAuth2AccessToken defaultOAuth2AccessToken = new DefaultOAuth2AccessToken(accessToken);

    // 设置额外用户信息
    UserInfo userInfo = ((UserInfoDetails) authentication.getPrincipal()).getUserInfo();
    userInfo.setPassword(null);
    // 将用户信息添加到token额外信息中
    defaultOAuth2AccessToken.getAdditionalInformation().put("USER_INFO", userInfo);

    return super.enhance(defaultOAuth2AccessToken, authentication);
  }

  /**
   * 解析token
   * @param value
   * @param map
   * @return
   */
  @Override
  public OAuth2AccessToken extractAccessToken(String value, Map<String, ?> map){
    OAuth2AccessToken oauth2AccessToken = super.extractAccessToken(value, map);
    Map<String, Object> additionalInfo = oauth2AccessToken.getAdditionalInformation();
    Object user_info = map.get("USER_INFO");
    additionalInfo.put("USER_INFO", user_info);
    return oauth2AccessToken;
  }

}
